﻿package com.sgcc.nfc.lock.presentation.warnings

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.domain.model.Warning
import com.sgcc.nfc.lock.domain.usecase.GetWarningDetailUseCase
import com.sgcc.nfc.lock.domain.usecase.HandleWarningUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.launch

@HiltViewModel
class WarningDetailViewModel @Inject constructor(
    private val getWarningDetailUseCase: GetWarningDetailUseCase,
    private val handleWarningUseCase: HandleWarningUseCase,
    savedStateHandle: SavedStateHandle
) : ViewModel() {

    private val warningId: Long = savedStateHandle.get<Long>("warningId") ?: 0L

    private val _warning = MutableLiveData<Warning?>()
    val warning: LiveData<Warning?> = _warning

    private val _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean> = _isLoading

    private val _message = MutableLiveData<String?>()
    val message: LiveData<String?> = _message

    init {
        loadDetail()
    }

    fun loadDetail() {
        viewModelScope.launch {
            _isLoading.value = true
            when (val result = getWarningDetailUseCase(warningId)) {
                is NetworkResult.Success -> _warning.value = result.data
                is NetworkResult.Error -> _message.value = result.message ?: "预警信息加载失败，请稍后重试"
                NetworkResult.Loading -> _isLoading.value = true
            }
            _isLoading.value = false
        }
    }

    fun handleWarning(remark: String?) {
        viewModelScope.launch {
            _isLoading.value = true
            when (val result = handleWarningUseCase(warningId, remark)) {
                is NetworkResult.Success -> {
                    _message.value = "预警处理成功"
                    loadDetail()
                }
                is NetworkResult.Error -> _message.value = result.message ?: "预警处理失败，请稍后重试"
                NetworkResult.Loading -> _isLoading.value = true
            }
            _isLoading.value = false
        }
    }
}
